<template>
  <a-drawer
      title="添加优惠券"
      :visible="visible"
      :destroyOnClose="true"
      :width="450"
      :body-style="{
      paddingBottom: '80px',
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflow: 'auto',
    }"
      :maskClosable="true"
      @close="closeModal"
  >
    <a-form layout="vertical">
      <a-form-item label="优惠券名称" v-bind="validateInfos.name">
        <a-input placeholder="请输入名称" v-model:value="modelRef.name"/>
      </a-form-item>

      <a-form-item v-bind="validateInfos.use_premise">
        <template #label>
          <span>优惠券使用条件</span>
          <a-tooltip placement="top">
            <template #title>
              满足金额：使用该券需要满足的账单支付总金额。
              <br/>
              账单月数：用户需要勾选连续的账单，账单合计需要满足的月数。例如一次性支付从1月1日-12月31日的12个月同一费用类型账单。
              <br/>
              账单个数：用户需要一次性支付几个绑定的费用类型的账单。
            </template>
            <QuestionCircleOutlined class="tips-coupon"/>
          </a-tooltip>
        </template>
        <a-row>
          <a-col :span="8">
            <a-select
                :options="USE_TYPE_OPTIONS"
                v-model:value="modelRef.use_premise.condition"
                class="w-100p"
            />
          </a-col>
          <a-col :span="16">
            <a-input-number
                :placeholder="useCouponInfo.placeholder"
                v-model:value="modelRef.use_premise.num"
                :min="modelRef.use_premise.condition === 'billPrice' ? 0.01 : 1"
                :precision="useCouponInfo.precision"
                class="w-100p"
            />
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item label="优惠券金额" v-bind="validateInfos.discounts">
        <a-row>
          <a-col :span="8">
            <a-select
                :options="DISCOUNTS_TYPE"
                v-model:value="modelRef.discounts.attribute"
                class="w-100p"
            />
          </a-col>
          <a-col :span="16">
            <a-input-number
                :placeholder="discountsInfo.placeholder"
                v-model:value="modelRef.discounts.amount"
                :min="modelRef.discounts.attribute === 1 ? 0.01 : 0.1"
                :precision="discountsInfo.precision"
                :max="modelRef.discounts.attribute === 1 ? Infinity : 9.9"
                class="have-unit"
            />
            <span class="unit-box">{{ modelRef.discounts.attribute === 1 ? '元' : '折' }}</span>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item
          label="绑定公司"
          v-bind="validateInfos.org_branch_id"
      >
        <a-select
            v-model:value="modelRef.org_branch_id"
            :options="companyList"
            placeholder="请绑定公司"
            class="w-100p"
            :allowClear="true"
        />
      </a-form-item>

      <a-form-item
          label="绑定项目"
          v-bind="validateInfos.village_id"
      >
        <a-select
            v-model:value="modelRef.village_id"
            :options="villageList"
            placeholder="请绑定项目"
            class="w-100p"
            :allowClear="true"
        />
      </a-form-item>

      <a-form-item v-bind="validateInfos.cost_type">
        <template #label>
          <span>费用类型</span>
          <TextTip tips="您需要绑定能使用该优惠券的费用类型，支持多选。"/>
        </template>
        <div class="cost-box">
          <a-button
              v-for="(item, index) in modelRef.cost_type"
              :key="index"
              shape="round"
              size="middle"
              class="btn-mb-8"
              style="margin-right: 10px"
          >
            <template #icon>
              {{ item.label }}
            </template>
            <CloseOutlined
                @click.stop="deleteCost(item)"
                style="font-size: 12px; margin-left: 4px"
            />
          </a-button>
          <a-button
              type="primary"
              class="btn-br btn-mb-8"
              ghost
              @click="addCostType"
          >选择费用类型
          </a-button
          >
        </div>
      </a-form-item>

      <a-form-item label="活动有效期" v-bind="validateInfos.validity">
        <a-range-picker
            class="w-100p"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            v-model:value="modelRef.validity"
            :disabled-date="disabledDate"
        >
          <template #suffixIcon>
            <CalendarOutlined/>
          </template>
        </a-range-picker>
      </a-form-item>

      <a-form-item label="优惠券数量" v-bind="validateInfos.num">
        <a-input-number
            class="w-100p"
            placeholder="不输入代表不限制数量"
            v-model:value="modelRef.num"
            :min="1"
            :precision="0"
        />
      </a-form-item>

      <a-form-item label="优惠券有效期" v-bind="validateInfos.effective_date">
        <a-row>
          <a-col :span="modelRef.effective_date.valide_date === 'date_3' ? 12 : 24">
            <a-select
                :options="LIFE_SPAN_OPTIONS"
                v-model:value="modelRef.effective_date.valide_date"
                class="w-100p"
            />
          </a-col>
          <a-col :span="12" v-if="modelRef.effective_date.valide_date === 'date_3'">
            <a-input-number
                placeholder="请输入有效天数"
                v-model:value="modelRef.effective_date.day"
                :min="1"
                :precision="0"
                class="have-unit"
            />
            <span class="unit-box">天</span>
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item label="每租客可领取数量" v-bind="validateInfos.got_num">
        <a-input-number
            class="w-100p"
            placeholder="不输入代表不限制数量"
            v-model:value="modelRef.got_num"
            :min="1"
            :precision="0"
        />
      </a-form-item>

      <a-form-item label="是否允许提前领券" v-bind="validateInfos.is_early">
        <a-switch
            :checkedValue="1"
            :unCheckedValue="0"
            v-model:checked="modelRef.is_early"
            checked-children="是"
            un-checked-children="否"
        />
      </a-form-item>

      <a-form-item label="用户自主领取优惠劵" v-bind="validateInfos.is_receive">
        <a-switch
            :checkedValue="1"
            :unCheckedValue="0"
            v-model:checked="modelRef.is_receive"
            checked-children="是"
            un-checked-children="否"
        />
      </a-form-item>

      <a-form-item label="优惠券使用说明" v-bind="validateInfos.desc">
        <a-textarea
            placeholder="请输入优惠券使用说明"
            :auto-size="{ minRows: 3 }"
            :maxlength="50"
            v-model:value="modelRef.desc"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" :loading="loading" @click.prevent="onSubmit">保存</a-button>
    </div>


    <SelectCostType
        :visible="selectCostVisible"
        :value="modelRef.cost_type"
        @closeModal="selectCostVisible = false"
        @costConfirm="costConfirm"
        :disabledBond="true"
    />

  </a-drawer>
</template>

<script>
import {computed, defineComponent, reactive, ref, toRaw, toRefs, watch} from "vue";
import {Form, message} from "ant-design-vue";
import request from "@/common/utils/request";
import {
  CalendarOutlined,
  CheckOutlined,
  QuestionCircleOutlined,
  CloseOutlined
} from "@ant-design/icons-vue";
import {TextTip} from "bl-common-vue3";
import store from "@/store";
import SelectCostType from "@/components/SelectCostType/index.vue";

const useForm = Form.useForm;
import _ from 'lodash';
import moment from "moment";

export default defineComponent({
  name: "AddCoupon",
  components: {
    SelectCostType,
    QuestionCircleOutlined,
    CalendarOutlined,
    CheckOutlined,
    CloseOutlined,
    TextTip,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, context) {

    const state = reactive({
      villageList: [],
      selectCostVisible: false,
      loading: false,
      companyList: [],
    });

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      name: "",
      // 使用条件
      use_premise: {
        condition: 'billPrice',
        num: '',
      },
      // 折扣
      discounts: {
        attribute: 1, // 1 金额 2 折扣
        amount: '',
      },
      org_branch_id: undefined,
      village_id: undefined,
      cost_type: [],
      validity: [], // 活动有效期
      num: '', // 优惠券数量
      // 优惠券有效期
      effective_date: {
        valide_date: 'date_1',
        day: '',
      },
      got_num: '', // 每租客可领取数量
      is_early: 1, // 是否允许提前领券
      is_receive: 1, // 用户自主领取优惠劵
      desc: '', // 优惠券使用说明
    });

    const disabledDate = (current) => {
      return current < moment().startOf("day");
    };

    const useCouponInfo = computed(
        () => USE_TYPE_OPTIONS.filter((v) => v.value === modelRef.use_premise.condition)[0]
    );

    const discountsInfo = computed(
        () => DISCOUNTS_TYPE.filter((v) => v.value === modelRef.discounts.attribute)[0]
    );

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      context.emit("closeModal");
    };

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      name: [{required: true, message: "必填项"}],
      use_premise: [{
        required: true,
        trigger: 'change',
        validator: (rules, value) => useConditionValidator(rules, value)
      }],
      discounts: [{
        required: true,
        trigger: 'change',
        validator: (rules, value) => useConditionValidator(rules, value)
      }],
      org_branch_id: [{required: true, message: "必填项"}],
      village_id: [{required: true, message: "必填项"}],
      cost_type: [{required: true, message: "费用类型必选"}],
      validity: [{required: true, message: "活动有效期必填"}],
      effective_date: [{
        required: true,
        trigger: 'change',
        validator: (rules, value) => lifeSpanValidator(rules, value)
      }],
    });

    const useConditionValidator = async (rules, value) => {
      if (rules.required) {
        let isAll = true
        for (let key in value) {
          if (!(value[key] || value[key] === 0)) {
            isAll = false
          }
        }
        if (!isAll) {
          return Promise.reject("必填项");
        }
      }
      return Promise.resolve();
    };

    // 选择费用类型
    const addCostType = () => {
      state.selectCostVisible = true;
    };

    // 选择费用类型-确定
    const costConfirm = (list) => {
      modelRef.cost_type = _.cloneDeep(list);
      state.selectCostVisible = false;
    };

    // 删除费用类型
    const deleteCost = (item) => {
      modelRef.cost_type = modelRef.cost_type.filter((v) => v.value !== item.value);
    };

    const lifeSpanValidator = async (rules, value) => {
      if (rules.required) {
        if (value.type === 'custom' && !(value.number || value.number === 0)) {
          return Promise.reject("有效天数必填");
        }
      }
      return Promise.resolve();
    };

    /**
     * @description: 创建表单
     */
    const {resetFields, validate, validateInfos} = useForm(
        modelRef,
        rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate()
          .then(() => {
            state.loading = true;
            let params = _.cloneDeep(modelRef);
            params.cost_type = modelRef.cost_type.map((v) => v.value);
            params.attribute = params.discounts.attribute;
            params.amount = params.discounts.amount;
            params.start_time = params.validity[0];
            params.end_time = params.validity[1];
            if (params.effective_date.valide_date !== 'date_3') {
              delete params.effective_date.day;
            }
            if (!params.num) {
              delete params.num
            }
            if (!params.got_num) {
              delete params.got_num
            }
            delete params.discounts;
            delete params.validity;
            request
                .post("/org", '/coupon/add', {...params})
                .then((res) => {
                  message.success("添加成功");
                  state.loading = false;
                  context.emit("addSuccess");
                }).catch(() => {
              state.loading = false;
            })
          })
    };

    const getVillageList = () => {
      request.get("/org", "/build/villageAndBuildList", {checked: 1}).then((res) => {
        state.villageList = res.villageList.map((item) => ({
          label: item.name,
          value: item.id,
          buildList: item.buildList,
        }));
      });
    };

    const getCompanyList = () => {
      request.get("/org", "/company/orgAndBranch").then(res => {
        console.log(res)
        state.companyList = res.list.map(item => {
          return {
            label: item.name,
            value: item.id,
          }
        })
      })
    }


    /**
     * @description: 初始化
     */
    const init = () => {
      getVillageList();
      getCompanyList();
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            // 打开时初始化数据
            init();
          } else {
            // 关闭时重置数据
            resetFields();
            state.villageList = [];
          }
        }
    );
    return {
      ...toRefs(state),
      validateInfos,
      resetFields,
      modelRef,
      USE_TYPE_OPTIONS,
      useCouponInfo,
      DISCOUNTS_TYPE,
      discountsInfo,
      LIFE_SPAN_OPTIONS,
      closeModal,
      onSubmit,
      addCostType,
      costConfirm,
      deleteCost,
      disabledDate,
    };
  },
});
const LIFE_SPAN_OPTIONS = [
  {
    value: "date_1",
    label: "领取后当天有效",
  },
  {
    value: "date_2",
    label: "同活动结束时间",
  },
  {
    value: "date_3",
    label: "自定义有效天数",
  },
];

const DISCOUNTS_TYPE = [
  {
    value: 1,
    label: "金额",
    placeholder: '请输入优惠金额',
    precision: 2,
  },
  {
    value: 2,
    label: "折扣",
    placeholder: '请输入优惠折扣',
    precision: 1,
  },
];

const USE_TYPE_OPTIONS = [
  {
    value: "billPrice",
    label: "满足金额",
    placeholder: '请输入满足金额',
    precision: 2,
  },
  {
    value: "billMonth",
    label: "账单月数",
    placeholder: '请输入需要满足的月数',
    precision: 0,
  },
  {
    value: "billCount",
    label: "账单个数",
    placeholder: '请输入需要满足的个数',
    precision: 0,
  },
];

</script>

<style lang="less" scoped>
.have-unit {
  width: calc(100% - 32px);
}

.unit-box {
  text-align: center;
  line-height: 30px;
  display: inline-block;
  width: 30px;
  height: 30px;
  background: #f2f2f2;
  border: 1px solid #d9d9d9;
  border-left: none;
}

.tips-coupon {
  margin-left: 5px;
  margin-right: 5px;
  color: rgb(153, 153, 153);
  font-size: 14px;
}

.btn-mb-8 {
  margin-bottom: 8px;
}
</style>
